﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Abp;
using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.RemoteEventBus;
using Abp.Runtime.Caching;
using Castle.Core.Logging;
using FwProject.Authorization.Users;
using FwProject.Comm;
using FwProject.Core.Distribution;
using FwProject.Core.Restaurant;
using FwProject.Core.SettlementInfoModel;
using FwProject.Distribution;
using FwProject.Distribution.Dto;
using FwProject.PrePaymentInfo;
using FwProject.PublicService.JPush;
using FwProject.Restaurant;
using FwProject.Users;
using Microsoft.EntityFrameworkCore;

namespace FwProject.RemoteEventBus
{
    /// <summary>
    /// 根据回库的车辆数据自动生成日结的收据和收款
    /// </summary>

    [RemoteEventHandler(ForType = RemoteTypeHelp.TYPERECEIVABLES, ForTopic = RemoteTypeHelp.TOPICDAYNOWLOADCAR)]
    public class DayNowReceivablesMessage : IRemoteEventHandler, ITransientDependency
    {
        public readonly ICacheManager _catchmanager;
        public readonly IJPushAppservice _jPushAppservice;
        public readonly IUserAppService _userAppService;
        public readonly IRepository<LoadCar, Guid> _repositoryLoadCar;//装车记录
        public readonly IRepository<RestaurantInfo, Guid> _repositoryRestaurantInfo;//餐厅信息
        public readonly IRepository<DistributionInfo, Guid> _repositoryDistributionInfo;//配送
        public readonly IRepository<DistributionInfoDetails, Guid> _repositoryDistributionInfoDetails;//配送明细
        public readonly IRepository<SettlementInfo, Guid> _repositorySettlementInfo;//收据生成
        public readonly IRepository<ReceiptInfoModel, Guid> _repositoryReceiptInfoModel;//收款单生成
        private readonly IRepository<User, long> _userRepository;
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        public IGuidGenerator _guid { get; set; }
        public ILogger logging { get; set; }
        public DayNowReceivablesMessage(ICacheManager catchmanager, IJPushAppservice jPushAppservice,
                                      IRepository<LoadCar, Guid> repositoryLoadCar,
                                      IUserAppService userAppService,
                                      IRepository<User, long> userRepository,
                                      IRepository<RestaurantInfo, Guid> repositoryRestaurantInfo,
                                      IRepository<DistributionInfo, Guid> repositoryDistributionInfo,
                                      IRepository<DistributionInfoDetails, Guid> repositoryDistributionInfoDetails,
                                      IRepository<SettlementInfo, Guid> repositorySettlementInfo,
                                      IRepository<ReceiptInfoModel, Guid> repositoryReceiptInfoModel,
                                      IUnitOfWorkManager unitOfWorkManager

                                      )
        {
            _repositoryRestaurantInfo = repositoryRestaurantInfo;
            _repositoryDistributionInfo = repositoryDistributionInfo;
            _repositoryDistributionInfoDetails = repositoryDistributionInfoDetails;
            _repositorySettlementInfo = repositorySettlementInfo;
            _repositoryReceiptInfoModel = repositoryReceiptInfoModel;
            _userRepository = userRepository;
            _repositoryLoadCar = repositoryLoadCar;
            _catchmanager = catchmanager;
            _jPushAppservice = jPushAppservice;
            logging = NullLogger.Instance;
            _userAppService = userAppService;
            _unitOfWorkManager = unitOfWorkManager;

        }
        [UnitOfWork]
        public void HandleEvent(RemoteEventArgs eventArgs)
        {
            using (var unitOfWork = _unitOfWorkManager.Begin())
            {
                try
                {
                    ///装车编号
                    var Id = Guid.Parse(eventArgs.EventData.Data[RemoteTypeHelp.MODELID].ToString());
                    var loadModel = _repositoryLoadCar.Get(Id);
                    //得到所有的餐厅
                    var dbyrId = _repositoryDistributionInfo.GetAll().Where(o => o.LoadCarId == loadModel.Id).Select(o => o.Restaurantid).ToArray();
                    //得到所有日结的餐厅
                    var rId = _repositoryRestaurantInfo.GetAll().Where(o => o.BalanceWay == BalanceWayEnum.日结 && dbyrId.Any(r => r == o.Id)).Select(o => o.Id);
                    foreach (var item in rId)
                    {
                        var model = _repositoryDistributionInfo.GetAllIncluding(o => o.DistributionInfoListDetails).Where(o => o.LoadCarId == Id && o.Restaurantid == item).FirstOrDefault();
                        if (model != null)
                        {
                            var sID = _guid.Create();
                            var ReceiptInfoId = _guid.Create();
                            model.SettlementId = sID;
                            model.Pricestatus = Pricestatus.已制单;
                            foreach (var m in model.DistributionInfoListDetails)
                            {
                                m.PricesId = sID;
                                m.Pricestatus = Pricestatus.已制单;
                            }
                            SettlementInfo settlementInfo = new SettlementInfo();
                            settlementInfo.Id = sID;
                            settlementInfo.FactoryinfoId = model.FactoryinfoId.Value;
                            settlementInfo.ExamineStatus = Core.SettlementInfoModel.ExamineStatus.已审核;
                            settlementInfo.ReceiptInfoId = ReceiptInfoId;
                            settlementInfo.Totalprice = model.TotalPrice;
                            settlementInfo.Restaurantid = model.Restaurantid;
                            settlementInfo.RestaurantPayStatus = RestaurantPayStatus.未收款;
                            settlementInfo.EmployeeDriverid = model.CreatorUserId;
                            settlementInfo.BalanceWayEnum = BalanceWayEnum.日结;
                            settlementInfo.Actualprice = model.TotalPrice;
                            settlementInfo.CreatorUserId = model.CreatorUserId;
                            settlementInfo.DeliveryDate = DateTime.Now.ToString("yyyy-MM-dd");
                            ///生成收据
                            _repositorySettlementInfo.InsertAndGetId(settlementInfo);

                        }



                    }


                }
                catch (Exception exe)
                {
                    logging.Info($"{nameof(DayNowReceivablesMessage)}{exe.ToString()}");

                }
                finally
                {
                    logging.Info($"{nameof(DayNowReceivablesMessage)}");
                }

                unitOfWork.Complete();
            }
        }
    }

}
